package se.vgregion.velocity.liferay.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * https://www.liferay.com/web/pmesotten/blog/-/blogs/inject-any-custom-class-or-service-into-web-content-templates
 */
@Component
public class SpringBeanLocator implements ApplicationContextAware {
 
    private static ApplicationContext ctx;
 
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String className) {
        try {
            return (T) ctx.getBean(Class.forName(className));
        } catch (BeansException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
 
    public void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;
    }
    
}